<template>
  <div class="image-select-list clearfix">
    <div
      v-for="(img, index) in list"
      :key="index"
      class="image-item">
        <img :src="img | imgUrl" alt="">
        <a class="close" @click="onRemove(index)">×</a>
      </div>
    <div
      v-if="showItemAdd"
      class="image-item image-item-add"
      @click="$refs.imageUploadDialog.show()">
      + 添加图片
    </div>
    <image-upload-dialog
      ref="imageUploadDialog"
      :multiple="multiple"
      @onSave="onDialogSubmit"/>
  </div>
</template>

<script>
import ImageUploadDialog from '@/components/ImageUploadDialog'

export default {
  name: 'ImageSelectList',
  props: {
    value: {
      type: Array,
      default: () => {
        return []
      }
    },
    single: Boolean
  },
  components: {
    ImageUploadDialog
  },
  data () {
    return {
      baseUrl: process.env.VUE_APP_BASE_URL,
      list: [],
      multiple: true
    }
  },
  created () {
    this.list = this.value
    this.multiple = !this.single
  },
  computed: {
    showItemAdd () {
      if (this.single) {
        return !(this.list.length > 0)
      } else {
        return true
      }
    }
  },
  methods: {
    onDialogSubmit (filesUpload) {
      filesUpload.map(file => {
        this.list.push((file.response || {}).path)
      })
      this.$emit('input', this.list)
      this.$emit('onChange', this.list)
      this.$refs.imageUploadDialog.close()
    },
    onRemove (index) {
      this.list.splice(index, 1)
      this.$emit('input', this.list)
      this.$emit('onChange', this.list)
    }
  },
  filters: {
    imgUrl (value) {
      return process.env.VUE_APP_BASE_URL + value
    }
  },
  watch: {
    value (val) {
      this.list = val
    }
  }
}
</script>

<style lang="scss" scoped>
.image-select-list {
  display: block;
}
.image-item {
  position: relative;
  float: left;
  margin: 0 10px 5px 0;
  width: 80px;
  height: 80px;
  border: 1px solid #ddd;
  background-color: #fff;
  position: relative;
  &>img {
    width: 100%;
    height: 100%;
    border: none;
  }
  &>.close {
    display: none;
    position: absolute;
    z-index: 2;
    top: -9px;
    right: -9px;
    width: 20px;
    height: 20px;
    font-size: 16px;
    line-height: 18px;
    color: #fff;
    text-align: center;
    cursor: pointer;
    background: hsla(0,0%,60%,.6);
    border-radius: 10px;
  }
  &:not(.image-item-add):hover {
    &>.close {
      display: block;
    }
  }
  &.image-item-add {
    line-height: 80px;
    text-align: center;
    cursor: pointer;
    font-size: 12px;
    color: #409EFF;
  }
}
</style>